
using System;
using System.Data;
using System.ComponentModel;

namespace stefc.geo.data
{
	/// <summary>
	/// Helper class for easy access SQLite database
	/// </summary>
	internal class DbHelper : IDisposable
	{

		private readonly IDbConnection connection;
		
		public DbHelper(IDbConnection connection)
		{
			this.connection=connection;
			this.connection.Open();
		}
		
		public void Dispose()
		{
			this.connection.Close();
		}
		
		public long GetPragma(string name)
		{
			object result = this.CreateCommand(String.Format("PRAGMA {0}",name)).ExecuteScalar();
			return Convert.ToInt64(result);
		}
		
		public void SetPragma(IDbTransaction transaction,string name, long value)
		{
			this.CreateCommand(transaction,String.Format("PRAGMA {0} = {1}",name, value)).ExecuteNonQuery();
		}
		
		public bool ExecuteNonQuery(string cmd)
		{
			return this.CreateCommand(cmd).ExecuteNonQuery() > 0;
		}
		
		public object ExecuteScalar(string cmd)
		{
			return this.CreateCommand(cmd).ExecuteScalar();
		}
		
		public IDataReader ExecuteReader(string cmd)
		{
			return this.CreateCommand(cmd).ExecuteReader();			
		}
		
		public IDbCommand CreateCommand(string sql)
		{
			return this.CreateCommand(null,sql);
		}
		
		public IDbCommand CreateCommand(IDbTransaction transaction, string sql)
		{
			IDbCommand cmd = this.connection.CreateCommand();
			cmd.CommandText = sql;
			cmd.CommandType = CommandType.Text;
			cmd.Transaction = transaction;
			return cmd;
		}
		
		public IDbTransaction BeginTransaction()
		{
			return this.connection.BeginTransaction();
		}
	}
}